'use strict';

const { Service } = require('egg');
const Budget = require('../model/budget');
const Expense = require('../model/expense');
const TravelPlan = require('../model/travel_plan');

class BudgetService extends Service {
    toDTO(budget, expenses = []) {
        const usedSum = expenses.reduce((s, e) => s + Number(e.amount || 0), 0);

        // 计算分类占比，而不是预算
        const categoryCounts = {};
        expenses.forEach(e => {
            if (!categoryCounts[e.category]) categoryCounts[e.category] = 0;
            categoryCounts[e.category] += Number(e.amount || 0);
        });

        const categoriesWithPercentage = Object.keys(categoryCounts).map(name => ({
            name,
            used: categoryCounts[name],
            percentage: usedSum > 0 ? (categoryCounts[name] / usedSum * 100).toFixed(2) : 0
        }));

        return {
            id: budget.id,
            userId: budget.user_id,
            travelPlanId: budget.travel_plan_id,
            title: budget.title,
            amount: Number(budget.amount || 0),
            usedAmount: usedSum,
            categories: categoriesWithPercentage,
        };
    }

    async list(userId) {
        const budgets = await Budget.findAll({
            where: { user_id: userId },
            order: [['created_at', 'DESC']],
        });

        // 聚合每个预算的支出
        const results = [];
        for (const b of budgets) {
            const expenses = await Expense.findAll({ where: { budget_id: b.id } });
            results.push(this.toDTO(b, expenses));
        }

        return { success: true, data: results };
    }

    async getById(id, userId) {
        const budget = await Budget.findOne({ where: { id, user_id: userId } });
        if (!budget) {
            return { success: false, message: '预算不存在或无权限' };
        }
        const expenses = await Expense.findAll({ where: { budget_id: id }, order: [['date', 'ASC']] });
        return {
            success: true, data: {
                budget: this.toDTO(budget, expenses), expenses: expenses.map(e => ({
                    id: e.id,
                    budgetId: e.budget_id,
                    userId: e.user_id,
                    category: e.category,
                    amount: Number(e.amount || 0),
                    currency: e.currency,
                    date: e.date,
                    description: e.description || '',
                }))
            }
        };
    }

    async create(userId, payload) {
        const { title, amount, travelPlanId } = payload;
        if (!title) return { success: false, message: '标题必填' };
        const budget = await Budget.create({
            user_id: userId,
            travel_plan_id: travelPlanId || null,
            title,
            amount: amount || 0,
        });
        return { success: true, data: this.toDTO(budget, []) };
    }

    async update(id, userId, payload) {
        const budget = await Budget.findOne({ where: { id, user_id: userId } });
        if (!budget) return { success: false, message: '预算不存在或无权限' };
        const { title, amount, travelPlanId } = payload;
        const updateFields = {};
        if (title !== undefined) updateFields.title = title;
        if (amount !== undefined) updateFields.amount = amount;
        if (travelPlanId !== undefined) updateFields.travel_plan_id = travelPlanId || null;
        await Budget.update(updateFields, { where: { id } });
        const updated = await Budget.findByPk(id);
        const expenses = await Expense.findAll({ where: { budget_id: id } });
        return { success: true, data: this.toDTO(updated, expenses) };
    }

    async destroy(id, userId) {
        const budget = await Budget.findOne({ where: { id, user_id: userId } });
        if (!budget) return { success: false, message: '预算不存在或无权限' };
        await Budget.destroy({ where: { id } });
        return { success: true };
    }
}

module.exports = BudgetService;